package com.ja.openchat.ui.contact.search;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.StringUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.google.gson.JsonObject;
import com.ja.openchat.AppViewModelFactory;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.databinding.ActivityHistoryChatSearchBinding;
import com.ja.openchat.ui.chat.ChatActivity;
import com.ja.openchat.ui.contact.ContactDetailActivity;
import com.ja.openchat.ui.contact.ContactDetailSingleActivity;
import com.ja.openchat.viewmodels.PublicChatSearchViewModel;
import com.ja.openchat.views.CustomEditText;
import com.zhy.view.flowlayout.FlowLayout;
import com.zhy.view.flowlayout.TagAdapter;
import com.zhy.view.flowlayout.TagFlowLayout;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.MessageInfo;
import com.zy.openchat.core.model.message.SearchMessagesFilter;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.SPUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseActivity;

/**
 * 公共搜索页面
 */
public class ChatHistorySearchActivity extends BaseActivity<ActivityHistoryChatSearchBinding, PublicChatSearchViewModel> implements View.OnClickListener {
    //分组列表
    private List<SearchSection> sectionList = new ArrayList<>();
    private PublicSearchSectionAdapter publicSearchSectionAdapter;
    private int searchPublicContactsTaskId;
    //聊天记录
    private List<MessageInfo> historyMsgList = new ArrayList<>();
    private int searchHistoryMsgTaskId;
    private List<String> searchDatas = new ArrayList<>();
    private TagAdapter tabAdapter;

    public static void start(BaseActivity activity, ChatInfo chatInfo,int filterType) {
        Intent intent = new Intent();
        intent.setClass(activity, ChatHistorySearchActivity.class);
        intent.putExtra("filterType",filterType);
        intent.putExtra("chatInfo", chatInfo);
        activity.startActivity(intent);
    }


    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_history_chat_search;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }


    @Override
    public PublicChatSearchViewModel initViewModel() {
        //使用自定义的ViewModelFactory来创建ViewModel，如果不重写该方法，则默认会调用LoginViewModel(@NonNull Application application)构造方法
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(PublicChatSearchViewModel.class);
    }
    private ChatInfo chatInfo;
    private SearchMessagesFilter searchMessagesFilter = null;
    @Override
    public void initView() {
        super.initView();
        int filterType = -1;
        if(getIntent()!=null){
            filterType = getIntent().getIntExtra("filterType",-1);
            chatInfo = getIntent().getParcelableExtra("chatInfo");

            switch (filterType){
                case 0:
                    searchMessagesFilter = new SearchMessagesFilter("searchMessagesFilterUrl");
                    break;
                case 1:
                    searchMessagesFilter = new SearchMessagesFilter("searchMessagesFilterPhotoAndVideo");
                    break;
                case 2:
                    searchMessagesFilter = new SearchMessagesFilter("searchMessagesFilterDocument");
                    break;
            }
        }
        String historyKeyWords = SPUtils.getString(this, "historyKeyWords", GsonUtils.toJson(searchDatas));
        searchDatas = GsonUtils.fromJson(historyKeyWords,GsonUtils.getListType(String.class));
        binding.toolbar.tvBarTitle.setText(getString(R.string.chat_history_search));
        binding.toolbar.ivBarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        KeyboardUtils.showSoftInput(binding.etSearch);
        //输入框监听
        binding.etSearch.setOnXTextChangeListener(new CustomEditText.OnXTextChangeListener() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                doSearch(s.toString());
            }
        });
        binding.linkBtn.setOnClickListener(this::onClick);
        binding.mediaBtn.setOnClickListener(this::onClick);
        binding.fileBtn.setOnClickListener(this::onClick);
        binding.tvCancel.setOnClickListener(this::onClick);

        setSearchLogView();
        initList();
        if(filterType!=-1){
            binding.filterLine1.setVisibility(View.GONE);
            binding.filterLine3.setVisibility(View.GONE);
            binding.linkBtn.setVisibility(View.GONE);
            binding.mediaBtn.setVisibility(View.GONE);
            binding.fileBtn.setVisibility(View.GONE);
            if(filterType==0){
                binding.toolbar.tvBarTitle.setText(getString(R.string.link_chat_history_search));
                binding.linkBtn.setVisibility(View.VISIBLE);
            }else if(filterType == 1){
                binding.etSearcView.setVisibility(View.GONE);
                binding.toolbar.tvBarTitle.setText(getString(R.string.media_chat_history_search));
                binding.mediaBtn.setVisibility(View.VISIBLE);
                requestFirstPage("");
            }else{
                binding.etSearcView.setVisibility(View.GONE);
                binding.toolbar.tvBarTitle.setText(getString(R.string.file_chat_history_search));
                binding.fileBtn.setVisibility(View.VISIBLE);
                requestFirstPage("");
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.linkBtn:
                start(this,chatInfo,0);
                break;
            case R.id.mediaBtn:
                start(this,chatInfo,1);
                break;
            case R.id.fileBtn:
                start(this,chatInfo,2);
                break;
            case R.id.tv_cancel:
                finish();
                break;
        }
    }

    private void setSearchLogView() {
        tabAdapter = new TagAdapter(searchDatas) {
            @Override
            public View getView(FlowLayout parent, int position, Object o) {
                TextView tv = (TextView) LayoutInflater.from(ChatHistorySearchActivity.this).inflate(R.layout.view_search_tag,
                        binding.historyTableLayout, false);
                tv.setText(searchDatas.get(position));
                return tv;
            }
        };
        binding.historyTableLayout.setAdapter(tabAdapter);
        binding.historyTableLayout.setOnTagClickListener(new TagFlowLayout.OnTagClickListener() {
            @Override
            public boolean onTagClick(final View view, int position, FlowLayout parent) {
                binding.etSearch.setText(searchDatas.get(position));
                return true;
            }
        });

    }

    private void initList() {
        //初始化列表
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        binding.recyclerView.setLayoutManager(layoutManager);
        publicSearchSectionAdapter = new PublicSearchSectionAdapter(R.layout.adapter_section_contact_list, sectionList);
        binding.recyclerView.setAdapter(publicSearchSectionAdapter);
        viewModel.setAdapter(publicSearchSectionAdapter);
        publicSearchSectionAdapter.setEmptyView(R.layout.status_center_empty_view);
        //点击事件
        publicSearchSectionAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                if (sectionList != null && sectionList.size() > 0 && position >= 0 && position < sectionList.size()) {
                    Object obj = sectionList.get(position).getObject();
                    if(chatInfo==null){
                        if (obj instanceof UserInfo) {
                            UserInfo user = (UserInfo) obj;
                            //跳转个人资料详情
//                            ContactDetailActivity.start(ChatHistorySearchActivity.this, user);
                            ContactDetailSingleActivity.start(ChatHistorySearchActivity.this, user);
                        }else if(obj instanceof MessageInfo){
                            MessageInfo messageInfo = (MessageInfo)obj;
                            ChatInfo chat = TelegramManager.getTelegramManager().getTgData().chatInfo(messageInfo.chat_id);
                            if(chat!=null){
                                ChatActivity.startActivity(ChatHistorySearchActivity.this,chat);
                            }
                        }
                    }else{
                        if(obj instanceof MessageInfo){
                            MessageInfo messageInfo = (MessageInfo)obj;
                            Intent intent = new Intent(ChatHistorySearchActivity.this,ChatActivity.class);
                            intent.putExtra("conversation",chatInfo);
                            intent.putExtra("messageId",messageInfo.id);
                            ChatHistorySearchActivity.this.startActivity(intent);
                        }
                    }

                }
            }
        });
        if(chatInfo!=null){
            publicSearchSectionAdapter.getLoadMoreModule().setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore() {
                    currentPage++;
                    requestByPage(currentPage,binding.etSearch.getText().toString());
                }
            });
        }
    }
    private int currentPage = 0;
    private void doSearch(String keyword) {
        if (searchPublicContactsTaskId > 0) {//结束之前的请求任务
            TelegramManager.getTelegramManager().cancelTask(searchPublicContactsTaskId);
        }
        if (searchHistoryMsgTaskId > 0) {//结束之前的请求任务
            TelegramManager.getTelegramManager().cancelTask(searchHistoryMsgTaskId);
        }
        //清除数据
        historyMsgList.clear();

        if (StringUtils.isEmpty(keyword)) {
            binding.initSearchView.setVisibility(View.VISIBLE);
            binding.recyclerView.setVisibility(View.GONE);
            reloadListUI(true);
            return;
        }
        requestFirstPage(keyword);
    }

    private void requestFirstPage(String keyword){
        binding.initSearchView.setVisibility(View.GONE);
        binding.recyclerView.setVisibility(View.VISIBLE);
        if(!TextUtils.isEmpty(keyword)){
            searchDatas.add(keyword);
        }
        currentPage = 0;
        requestByPage(0,keyword);
        //重新加载页面
        reloadListUI(true);
    }

    private void requestByPage(final int page,String keyword){
        TgResultBlock<List<MessageInfo>> tgResultBlock = new TgResultBlock<List<MessageInfo>>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, List<MessageInfo> obj) {
                if(page == 0){
                    if(obj!=null&&obj.size()>0){
                        historyMsgList.addAll(obj);
                    }else{
                        publicSearchSectionAdapter.getLoadMoreModule().loadMoreEnd(true);
                    }
                    reloadListUI(page==0);
                }else{
                    if(obj!=null&&obj.size()>0){
                        historyMsgList.addAll(obj);
                        reloadListUI(page==0);
                    }else{
                        publicSearchSectionAdapter.getLoadMoreModule().loadMoreEnd(true);
                    }

                }

            }

            @Override
            public void onTimeout(Map<String, Object> request) {

            }
        };
        if(chatInfo!=null){
            TelegramManager.getTelegramManager().searchChatMessages(this,chatInfo.id,searchMessagesFilter, 0,keyword,page,20,tgResultBlock);
        }else{
            TelegramManager.getTelegramManager().searchMessagesList(this, keyword, tgResultBlock);
        }
    }

    // "聊天记录"
    private void reloadListUI(boolean isFirstPage) {
        if(isFirstPage){
            sectionList.clear();
        }
        if (historyMsgList.size() > 0) {//好友
            sectionList.add(new SearchSection(true, new SearchSectionInfo(getString(R.string.chat_record)), SearchSection.SearchSectionType_HisMsgs));
            for (MessageInfo msg : historyMsgList) {
                sectionList.add(new SearchSection(false, msg, SearchSection.SearchSectionType_HisMsgs));
            }
        }
        publicSearchSectionAdapter.notifyDataSetChanged();
    }


    @Override
    protected void onStop() {
        super.onStop();
        SPUtils.putString(this,"historyKeyWords", GsonUtils.toJson(searchDatas));
    }
}
